<template>
	<view class="cart-page">
		<!-- 标题栏 -->
		<view class="page-header">
			<text class="title">我的购物车</text>
			<view class="decor-line"></view>
		</view>

		<!-- 购物车列表 -->
		<scroll-view scroll-y class="cart-list">
			<view class="cart-card" v-for="item in cartList" :key="item.id">
				<view class="select-box" @click="toggleSelect(item)">
					<view class="cuIcon-check" :class="{ checked: item.checked  }"></view>
				</view>

				<image class="product-image" :src="_imgUrl + item.photo" mode="aspectFill"></image>

				<view class="product-info">
					<text class="product-title">{{ item.name }}</text>
					<view class="price-section">
						<text class="price">¥{{ item.price }}</text>
						<view class="quantity-control">
							<view class="cuIcon-move" v-if="item.spNumber > 1" @click="changeQuantity(item, -1)"></view>
							<text class="quantity">{{ item.spNumber }}</text>
							<view class="cuIcon-add" @click="changeQuantity(item, 1)"></view>
						</view>
					</view>
				</view>

				<view class="delete-btn" @click="deleteItem(item.id)">
					<view class="cuIcon-delete"></view>
				</view>
			</view>
		</scroll-view>

		<!-- 结算栏 -->
		<view class="settlement-bar">
			<view class="check-all" @click="toggleAll">
				<view class="cuIcon-check" :class="{ checked: isAllChecked }"></view>
				<text>全选</text>
			</view>
			<view class="total-section">
				<text>合计：</text>
				<text class="total-price">¥{{ totalPrice }}</text>
			</view>
			<view class="settle-btn" @click="handleSettlement">去结算({{ checkedCount }})</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				cartList: [
					// {
					//   id: 1,
					//   name: "有机新鲜蔬菜礼盒",
					//   price: 68.0,
					//   quantity: 2,
					//   image: "/static/goods/vegetables.jpg",
					//   checked: true,
					// },
					// {
					//   id: 2,
					//   name: "农家土鸡蛋30枚装",
					//   price: 45.0,
					//   quantity: 1,
					//   image: "/static/goods/eggs.jpg",
					//   checked: false,
					// },
					// {
					//   id: 3,
					//   name: "新鲜水果套餐",
					//   price: 88.0,
					//   quantity: 1,
					//   image: "/static/goods/fruits.jpg",
					//   checked: true,
					// },
				],
				_imgUrl: "",
				ranking: {},
				nonghurangking: {},
			};
		},
		computed: {
			totalPrice() {
				return this.cartList
					.filter((item) => item.checked)
					.reduce((sum, item) => sum + item.price * item.spNumber, 0)
					.toFixed(2);
			},
			checkedCount() {
				return this.cartList.filter((item) => item.checked).length;
			},
			isAllChecked() {
				return this.cartList.every((item) => item.checked);
			},
		},
		onLoad() {
			this._imgUrl = this.$base.url;
			Promise.all([
				this.getcartList(),
				this.getrankingList("yonghu"),
				this.getrankingList("nonghu"),
			]);
		},
		methods: {
			async getcartList() {
				try {
					let res = await this.$api.list("cart", {
						userId: uni.getStorageSync("userInfo").userId,
					});
					if (res.code == 200) {
						// res.rows.checked = 
						res.rows.forEach((item) => {

							item.checked = item.status == "false" ? false : true
						})
						this.cartList = res.rows;
					}
				} catch (error) {
					//TODO handle the exception
				}
			},
			// 修改数量
			async changeQuantity(item, num) {
				const newNumber = item.spNumber + num;
				try {
					let res = await this.$api.update("cart", {
						...item,
						spNumber: newNumber,
					});
					if (res.code == 200) {
						this.getcartList();
					}
				} catch (error) {
					//TODO handle the exception
				}
				// this.cartList = this.cartList.map(item => {
				// 	if (item.id === id) {
				// 		const newQuantity = item.quantity + num
				// 		return {
				// 			...item,
				// 			quantity: newQuantity < 1 ? 1 : newQuantity
				// 		}
				// 	}
				// 	return item
				// })
			},

			// 切换选中状态
			async toggleSelect(cart) {
				// this.cartList = this.cartList.map((item) =>
				// 	item.id === cart.id ? {
				// 		...item,
				// 		checked: !item.checked,
				// 	} :
				// 	item
				// );
				// 
				console.log('选择', cart.checked)
				try {
					let res = await this.$api.update("cart", {
						...cart,
						status: cart.checked ? "false" :  "true"
					});
					// log
					if (res.code == 200) {
						this.getcartList();
					}
				} catch (error) {
					//TODO handle the exception
				}
			},

			// 全选/反选
			async toggleAll() {
				const targetStatus = !this.isAllChecked;
				// this.cartList = this.cartList.map((item) => ({
				// 	...item,
				// 	checked: targetStatus,
				// }));
				this.cartList = this.cartList.forEach((item) => {
					this.toggleSelect(item)
				})
			},

			// 删除商品
			async deleteItem(id) {
				uni.showModal({
					title: "提示",
					content: "确定要删除该商品吗？",
					success: async (res) => {
						// 修正1：统一缩进格式
						if (res.confirm) {
							try {
								let response = await this.$api.del("cart", id);

								if (response.code === 200) {
									await this.getcartList();

									uni.showToast({
										title: "删除成功",
										icon: "success",
									});
								} else {
									uni.showToast({
										title: `删除失败: ${response.msg}`,
										icon: "none",
									});
								}
							} catch (error) {
								console.error("删除操作异常:", error);
								uni.showToast({
									title: "网络异常，请稍后重试",
									icon: "none",
								});
							}
						}
					},
				});
			},

			async getrankingList(type) {
				let params = {};
				if (type == "yonghu") {
					params = {
						jfType: "yonghu",
						userId: uni.getStorageSync("userInfo").userId,
					};
				} else {
					params = {
						jfType: "nonghu",
						userId: uni.getStorageSync("userInfo").userId,
					};
				}

				try {
					let res = await this.$api.list("points", params);
					if (res.code === 200) {
						if (type == "yonghu") {
							this.ranking = res.rows[0];
						} else {
							this.nonghurangking = res.rows[0];
						}
					}
				} catch (error) {}
			},
			async updatepoints(item) {
				let params = {};
				if (type == "yonghu") {
					params = {
						id: this.ranking.id,
						pointsValue: this.ranking.pointsValue + this.ruleForm.jiage,
					};
				} else {
					params = {
						id: this.ranking.id,
						pointsValue: this.ranking.pointsValue + this.ruleForm.jiage,
					};
				}
				await this.$api.update(`points`, params);
			},
			async addDbPointsFun(data) {
				console.log('this.ruleForm', data)
				let params = {
					shangpinId: data.shangpinId,
					orderNum: data.spNumber,
					orderPrice: data.price,
					jfType: "nonghu",
				};

				try {
					let res = this.$api.addDbPoints(params)
				} catch (error) {
					//TODO handle the exception
				}
			},
			async addpoints(type, data) {
				let params = {};
				if (type == "yonghu") {
					params = {
						userId: uni.getStorageSync("userInfo").userId,
						userName: uni.getStorageSync("userInfo").userName,
						pointsValue: data.price,
						jfType: uni.getStorageSync("roles"),
					};
				}
				await this.$api.add(`points`, params);
			},
			async handleSettlement() {
				let that = this
				try {
					console.log(this.checkedCount);
					// 1. 校验选中商品
					if (this.checkedCount === 0) {
						return uni.showToast({
							title: "请选择要结算的商品",
							icon: "none",
						});
					}

					// 2. 显示加载状态
					uni.showLoading({
						title: "结算中...",
						mask: true,
					});

					// 3. 并行处理选中的商品
					const promises = this.cartList
						.filter((item) => item.checked)
						.map(async (item) => {
							try {
								// 3.1 创建订单
								const orderParams = {
									...item,
									cartId: item.id,
									remark: item.remark,
									status:""
								};

								// 3.2 提交订单（等待订单创建成功）
								const createRes = await this.$api.add("order", orderParams);

								if (createRes.code !== 200) {
									throw new Error(createRes.msg || "订单创建失败");
								}
								Promise.all([that.addDbPointsFun(item)]).then(async () => {
									if (that.ranking) {
										await that.$api.update(`points`, {
											id: that.ranking.id,
											pointsValue: that.ranking.pointsValue + item
												.price * item.spNumber,
										});
									} else {
										await that.addpoints("yonghu", item)
									}
								}).then(async () => {
									// 3.3 删除购物车项（订单创建成功后删除）
									const deleteRes = await this.$api.del("cart", item.id);


									if (deleteRes.code !== 200) {
										throw new Error(deleteRes.msg || "购物车删除失败");
									}
								}).then(() => {
									this.getcartList();
								}).catch((error) => {
									console.error("Error in Promise.all:", error);
								});



								return {
									success: true,
									id: item.id,
								};
							} catch (error) {
								console.error(`商品 ${item.name} 处理失败:`, error);
								return {
									success: false,
									id: item.id,
									message: error.message,
								};
							}
						});

					// 4. 等待所有操作完成
					const results = await Promise.all(promises);

					// 5. 处理结果
					const successItems = results.filter((r) => r.success);
					const failedItems = results.filter((r) => !r.success);

					// 6. 刷新购物车列表


					// 7. 关闭加载状态
					uni.hideLoading();

					// 8. 结果提示
					if (failedItems.length > 0) {
						uni.showModal({
							title: "部分商品结算失败",
							content: `成功结算 ${successItems.length} 件，失败 ${failedItems.length} 件`,
							showCancel: false,
						});
					} else {
						uni.showToast({
							title: `成功结算 ${successItems.length} 件商品`,
						});
					}

					// 9. 跳转订单页面（仅在全部成功时跳转）
					if (failedItems.length === 0) {
						uni.navigateTo({
							url: "/pages/order/create",
						});
					}
				} catch (error) {
					console.error("结算流程异常:", error);
					uni.hideLoading();
					uni.showToast({
						title: error.message || "结算过程发生异常",
						icon: "none",
					});
				}
			},
		},
	};
</script>

<style lang="scss" scoped>
	.cart-page {
		background: linear-gradient(15deg, #f8f9ff 0%, #f1f3fe 100%);
		min-height: 100vh;
	}

	.page-header {
		padding: 48rpx 32rpx 24rpx;

		.title {
			font-size: 48rpx;
			font-weight: 600;
			color: #2d3748;
		}

		.decor-line {
			height: 4rpx;
			width: 80rpx;
			background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
			margin-top: 16rpx;
		}
	}

	.cart-list {
		padding: 0 32rpx;
		height: calc(100vh - 280rpx);
	}

	.cart-card {
		background: rgba(255, 255, 255, 0.95);
		backdrop-filter: blur(20rpx);
		border-radius: 24rpx;
		padding: 32rpx;
		margin-bottom: 24rpx;
		display: flex;
		align-items: center;
		box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.1);

		.select-box {
			padding-right: 24rpx;

			.cuIcon-check {
				font-size: 40rpx;
				color: #c0c4cc;

				&.checked {
					color: #667eea;
				}
			}
		}

		.product-image {
			width: 160rpx;
			height: 160rpx;
			border-radius: 16rpx;
			margin-right: 24rpx;
		}

		.product-info {
			flex: 1;

			.product-title {
				font-size: 28rpx;
				color: #2d3748;
				line-height: 1.4;
				display: -webkit-box;
				-webkit-line-clamp: 2;
				-webkit-box-orient: vertical;
				overflow: hidden;
			}

			.price-section {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-top: 24rpx;

				.price {
					color: #ff4757;
					font-size: 32rpx;
					font-weight: 700;
				}

				.quantity-control {
					display: flex;
					align-items: center;
					background: #f8f9ff;
					border-radius: 40rpx;
					padding: 8rpx;

					.cuIcon {
						font-size: 32rpx;
						color: #667eea;
						padding: 8rpx 16rpx;
					}

					.quantity {
						min-width: 60rpx;
						text-align: center;
						font-size: 28rpx;
						color: #4a5568;
					}
				}
			}
		}

		.delete-btn {
			padding-left: 24rpx;

			.cuIcon-delete {
				font-size: 40rpx;
				color: #ff4757;
			}
		}
	}

	.settlement-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 120rpx;
		background: rgba(255, 255, 255, 0.95);
		backdrop-filter: blur(20rpx);
		display: flex;
		align-items: center;
		padding: 0 32rpx;
		box-shadow: 0 -4rpx 16rpx rgba(102, 126, 234, 0.1);

		.check-all {
			display: flex;
			align-items: center;

			.cuIcon-check {
				font-size: 40rpx;
				color: #fff;
				margin-right: 16rpx;

				&.checked {
					color: #2c25ea;
				}
			}
		}

		.total-section {
			flex: 1;
			padding: 0 32rpx;

			.total-price {
				color: #ff4757;
				font-weight: 700;
			}
		}

		.settle-btn {
			background: linear-gradient(135deg, #667eea, #764ba2);
			color: white;
			padding: 16rpx 48rpx;
			border-radius: 40rpx;
			font-size: 28rpx;
			box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
		}
	}
</style>